package com.zhengxiang.onlinexamination.controller;


import com.baomidou.mybatisplus.extension.api.ApiController;
import com.zhengxiang.onlinexamination.base.AjaxResult;
import com.zhengxiang.onlinexamination.base.BaseController;
import com.zhengxiang.onlinexamination.base.UserConstants;
import com.zhengxiang.onlinexamination.component.annotation.Anonymous;
import com.zhengxiang.onlinexamination.entity.SysUser;
import com.zhengxiang.onlinexamination.entity.vo.SysPostVo;
import com.zhengxiang.onlinexamination.entity.vo.SysUserVo;
import com.zhengxiang.onlinexamination.service.SysUserService;
import com.zhengxiang.onlinexamination.utils.SecurityUtils;
import com.zhengxiang.onlinexamination.utils.StringUtils;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import static com.zhengxiang.onlinexamination.utils.SecurityUtils.getUsername;

/**
 * 管理用户(SysUser)表控制层
 *
 * @author
 * @since 2023-03-11 10:23:24
 */
@RestController
@RequestMapping("sysUser")
public class SysUserController extends BaseController {

    @Autowired
    private SysUserService userService;

    /**
     * 新增用户
     */
    @PostMapping("/addSysUser")
    public AjaxResult add(@RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserAccount()))) {
            return AjaxResult.error("新增用户'" + user.getUserAccount() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhoneNumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserAccount() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserAccount() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setUserPassword(SecurityUtils.encryptPassword(user.getUserPassword()));
        userService.insertUser(user);
        return AjaxResult.success();
    }

    /**
     * 列表
     */
    @PostMapping("/pageList")
    public AjaxResult pageList(@RequestBody SysUserVo sysUserVo) {
        return AjaxResult.success(userService.pageList(sysUserVo));
    }

    /**
     * 删除用户
     */
    @GetMapping("/delSysUser")
    public AjaxResult delSysUser(SysUserVo sysUserVo) {
        userService.delSysUser(sysUserVo);
        return AjaxResult.success();
    }

    /**
     * 更新用户信息
     * */
    @PostMapping("/updateSysUser")
    public AjaxResult updateSysUser(@RequestBody SysUserVo sysUserVo){
        userService.updateSysUser(sysUserVo);
        return AjaxResult.success();
    }
}

